﻿using OpenQA.Selenium.Chrome;
using System;
using System.Threading;
using OpenQA.Selenium;
using System.IO;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using SeleniumExtras.WaitHelpers;
using RestSharp;
using SSharing.Frameworks.NetCore.Common.Extends;
using SeleniumDemo.ConsoleSite.Entity;
using Polly;
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.DevTools.V96.Network;
using EnableCommandSettings = OpenQA.Selenium.DevTools.V96.Network.EnableCommandSettings;

namespace SeleniumDemo.ConsoleSite
{
    class Program
    {
        static void Main(string[] args)
        {
            //第一个Selenium项目
            //HelloSelenium();

            //Selenium八大元素定位方法
            //EightFindElementMethod();

            //WebDriver核心方法和属性
            //WebDriverCoreMethodProperty();

            //WebElement核心属性和方法
            //WebElementCoreMethodProperty();

            //form表单
            //TestForm();

            //checkbox和radiobutton
            //TestCheckBoxRadioButton();

            //select下拉列表
            //TestSelect();

            //弹窗
            //TestPopWin();

            //三种等待方式
            //ThreeKindsWaiting();

            //17种等待条件
            //SeventeenWaitingCondition();

            //动作链，包括一系列的鼠标和键盘操作
            //TestActionChains();

            //执行javascript方法
            //TestExecuteJavascript();

            //屏幕截屏
            //TestScreenShot();

            //操作iframe
            //TestFrame();

            //测试天天基金登录
            //Test1234567Login();

            //测试自动获取Cookie
            //TestCookies();

            //模拟东财登录
            //LoginEastMoney();

            //TestSelenium4();

            //测试Network events
            TestSeleniumDevTools();

            Console.ReadKey();
        }

        static void TestSeleniumDevTools()
        {
            Random rnd = new Random();
            var chromeOptions = new ChromeOptions();
            //移除浏览器控制标志
            chromeOptions.AddExcludedArgument("enable-automation");
            //chromeOptions.AddAdditionalCapability("useAutomationExtension", false);
            chromeOptions.AddAdditionalOption("useAutomationExtension", false);

            //设置用户代理
            chromeOptions.AddArgument("--user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36");

            //去掉webdriver特征
            chromeOptions.AddArgument("--disable-blink-features=AutomationControlled");

            using (var driver = new ChromeDriver(chromeOptions))
            {
                driver.Navigate().GoToUrl("https://jywg.18.cn/Login");
                driver.Manage().Window.Maximize();
                Thread.Sleep(rnd.Next(2000, 3000));

                //输入帐号密码
                driver.FindElement(By.Id("txtZjzh")).Clear();//先清空
                driver.FindElement(By.Id("txtZjzh")).SendKeys("541400292043");
                Thread.Sleep(rnd.Next(2000, 3000));

                driver.FindElement(By.Id("txtPwd")).Clear();
                driver.FindElement(By.Id("txtPwd")).SendKeys("145073");
                Thread.Sleep(rnd.Next(2000, 3000));

                var tbcook = driver.FindElement(By.Id("rdsc45"));
                if (!tbcook.Selected)
                {
                    tbcook.Click();
                }
                Thread.Sleep(rnd.Next(2000, 3000));

                //获取验证码并提交表单，如果失败则重试，最多重试5次
                var validCodeEle = driver.FindElement(By.Id("imgValidCode"));
                var policy = Policy.Handle<WebDriverTimeoutException>(p => p != null).OrResult<bool>(p => !p).Retry(3);
                var getImgValidCodeResult = policy.Execute(() =>
                {
                    return Login(driver, validCodeEle);
                });
                Console.WriteLine("登录成功！");

                //获取cookie
                Dictionary<string, string> dicCookies = new Dictionary<string, string>();
                var cookies = driver.Manage().Cookies.AllCookies.ToList();
                if (cookies != null && cookies.Count > 0)
                {
                    foreach (var cookie in cookies)
                    {
                        dicCookies.Add(cookie.Name, cookie.Value);
                    }
                }
                Console.WriteLine(string.Format("获取cookie成功，共:{0}个！", dicCookies.Count));

                //获取validatekey，通过dev tools
                var session = driver.GetDevToolsSession();
                NetworkAdapter networkAdapter = new NetworkAdapter(session);
                networkAdapter.Enable(new EnableCommandSettings()).GetAwaiter().GetResult();
                networkAdapter.ResponseReceived += (sender, e) =>
                {
                    var mimeType = e.Response.MimeType;
                    var url = e.Response.Url;
                    if (mimeType == "application/json" && url.Contains("validatekey"))
                    {
                        //Console.WriteLine($"Url: { e.Response.Url } Status: { e.Response.Status } Type: { e.Response.MimeType } ");
                        var queryString = url.Substring(url.IndexOf('?'));
                        var arr = queryString.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                        var validateKey = arr[1];
                        Console.WriteLine("validateKey：" + validateKey);
                    }

                    //all
                    //Console.WriteLine($"Url: { e.Response.Url } Status: { e.Response.Status } Type: { e.Response.MimeType } ");
                };
                driver.Navigate().GoToUrl("https://jywg.18.cn/Trade/NewBuy");
                Thread.Sleep(5000);

                //关闭
                driver.Quit();
            }
        }

        static void TestSelenium4()
        {
            using (var driver = new ChromeDriver())
            {
                //var session = driver.GetDevToolsSession();

                //// add response received handler to dev tools session
                //NetworkAdapter networkAdapter = new NetworkAdapter(session);
                //networkAdapter.Enable(new EnableCommandSettings()).GetAwaiter().GetResult();
                //networkAdapter.ResponseReceived += NetworkAdapter_ResponseReceived;
                //driver.Navigate().GoToUrl("https://stackoverflow.com/");
                //Thread.Sleep(15000);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 模拟东财登录
        /// </summary>
        static void LoginEastMoney()
        {
            Random rnd = new Random();
            var chromeOptions = new ChromeOptions();
            //移除浏览器控制标志
            chromeOptions.AddExcludedArgument("enable-automation");
            //chromeOptions.AddAdditionalCapability("useAutomationExtension", false);
            chromeOptions.AddAdditionalOption("useAutomationExtension", false);

            //设置用户代理
            chromeOptions.AddArgument("--user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36");

            //去掉webdriver特征
            chromeOptions.AddArgument("--disable-blink-features=AutomationControlled");

            using (var driver = new ChromeDriver(chromeOptions))
            {
                driver.Navigate().GoToUrl("https://jywg.18.cn/Login");
                driver.Manage().Window.Maximize();
                Thread.Sleep(rnd.Next(2000, 3000));

                //输入帐号密码
                driver.FindElement(By.Id("txtZjzh")).Clear();//先清空
                driver.FindElement(By.Id("txtZjzh")).SendKeys("541400292043");
                Thread.Sleep(rnd.Next(2000, 3000));

                driver.FindElement(By.Id("txtPwd")).Clear();
                driver.FindElement(By.Id("txtPwd")).SendKeys("145073");
                Thread.Sleep(rnd.Next(2000, 3000));

                var tbcook = driver.FindElement(By.Id("rdsc45"));
                if (!tbcook.Selected)
                {
                    tbcook.Click();
                }
                Thread.Sleep(rnd.Next(2000, 3000));

                //获取验证码并提交表单，如果失败则重试，最多重试5次
                var validCodeEle = driver.FindElement(By.Id("imgValidCode"));
                var policy = Policy.Handle<TimeoutException>(p => p != null).OrResult<bool>(p => !p).Retry(3);
                var getImgValidCodeResult = policy.Execute(() =>
                {
                    return Login(driver, validCodeEle);
                });
                Console.WriteLine("登录成功！");

                //获取cookie
                Dictionary<string, string> dicCookies = new Dictionary<string, string>();
                var cookies = driver.Manage().Cookies.AllCookies.ToList();
                if (cookies != null && cookies.Count > 0)
                {
                    foreach (var cookie in cookies)
                    {
                        dicCookies.Add(cookie.Name, cookie.Value);
                    }
                }
                Console.WriteLine(string.Format("获取cookie成功，共:{0}个！", dicCookies.Count));

                //进入菜单新股新债/新债批量申购
                driver.Navigate().GoToUrl("https://jywg.18.cn/Trade/NewBuy");
                Thread.Sleep(rnd.Next(2000, 3000));

                driver.Navigate().GoToUrl("https://jywg.18.cn/Trade/XzsgBatPurchase");
                Thread.Sleep(rnd.Next(2000, 3000));

                //获取新债列表
                var trNewBonds = driver.FindElements(By.XPath("//*[@id='tableBody']/tr"));
                if (trNewBonds.HasValue())
                {
                    var tr0 = trNewBonds[0];
                    var td1 = tr0.FindElement(By.XPath("//tr/td[1]"));
                    var hasNewBonds = !(td1.Text.Contains("暂无数据"));
                    if (hasNewBonds)
                    {
                        var chkAll = driver.FindElement(By.XPath("//*[@id='chk_all']"));
                        if (!chkAll.Selected)
                        {
                            chkAll.Click();
                        }
                        Thread.Sleep(rnd.Next(2000, 3000));

                        driver.FindElement(By.XPath("//*[@id='btnBatBuy']")).Click();
                        Thread.Sleep(rnd.Next(2000, 3000));

                        driver.FindElement(By.XPath("//*[@id='btnConfirm']")).Click();
                        Thread.Sleep(rnd.Next(2000, 3000));

                        var cxcInfo = driver.FindElement(By.XPath("//*[@id='Cxc_Dialog']/div/div/div/p[1]"));
                        var cxcMessage = cxcInfo.Text;
                        if (cxcMessage.Contains("下单失败"))
                        {
                            Console.WriteLine("下单失败！");
                        }

                        driver.FindElement(By.XPath("//*[@id='btnCxcConfirm']")).Click();
                    }
                }

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 测试自动获取Cookie
        /// </summary>
        static void TestCookies()
        {
            //先登录然后获取cookie
            using (var driver = new ChromeDriver())
            {
                driver.Navigate().GoToUrl("https://login.1234567.com.cn/login");
                driver.Manage().Window.Maximize();
                Thread.Sleep(3000);

                //登录
                driver.FindElement(By.Id("tbname")).Clear();//先清空
                driver.FindElement(By.Id("tbname")).SendKeys("421125198410225252");

                driver.FindElement(By.Id("tbpwd")).Clear();
                driver.FindElement(By.Id("tbpwd")).SendKeys("145073abc");
                var tbcook = driver.FindElement(By.Id("tbcook"));
                if (!tbcook.Selected)
                {
                    tbcook.Click();
                }
                Thread.Sleep(3000);

                //提交表单
                driver.FindElement(By.Id("btn_login")).Click();
                Thread.Sleep(3000);

                //显示等待表单提交
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TitleContains("资产概览"));
                Console.WriteLine("登录成功!");

                //获取cookie
                Dictionary<string, string> dicCookies = new Dictionary<string, string>();
                var cookies = driver.Manage().Cookies.AllCookies.ToList();
                if (cookies != null && cookies.Count > 0)
                {
                    foreach (var cookie in cookies)
                    {
                        dicCookies.Add(cookie.Name, cookie.Value);
                    }
                }
                Console.WriteLine("获取cookie成功!");

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 测试天天基金登录
        /// </summary>
        static void Test1234567Login()
        {
            using (var driver = new ChromeDriver())
            {
                driver.Navigate().GoToUrl("https://login.1234567.com.cn/login");
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);

                driver.FindElement(By.Id("tbname")).Clear();//先清空
                driver.FindElement(By.Id("tbname")).SendKeys("421125198410225252");

                driver.FindElement(By.Id("tbpwd")).Clear();
                driver.FindElement(By.Id("tbpwd")).SendKeys("145073abc");
                var tbcook = driver.FindElement(By.Id("tbcook"));
                if (!tbcook.Selected)
                {
                    tbcook.Click();
                }
                Thread.Sleep(2000);

                //提交表单
                driver.FindElement(By.Id("btn_login")).Click();
                Thread.Sleep(2000);

                //显示等待表单提交
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TitleContains("资产概览"));
                Console.WriteLine("登录成功!");

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 操作iframe
        /// </summary>
        static void TestFrame()
        {
            using (var driver = new ChromeDriver())
            {
                //打开sahitest
                driver.Navigate().GoToUrl("http://sahitest.com/demo/framesTest.htm");
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);

                //操作frameset
                var topFrame = driver.FindElement(By.Name("top"));
                driver.SwitchTo().Frame(topFrame);
                driver.FindElement(By.XPath("/html/body/table/tbody/tr/td[1]/a[1]")).Click();
                Thread.Sleep(2000);

                //回到主页
                driver.SwitchTo().DefaultContent();
                Thread.Sleep(2000);

                var secondFrame = driver.FindElement(By.XPath("/html/frameset/frame[2]"));
                driver.SwitchTo().Frame(secondFrame);
                driver.FindElement(By.XPath("/html/body/table/tbody/tr/td[1]/a[3]")).Click();
                Thread.Sleep(2000);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 屏幕截屏
        /// </summary>
        static void TestScreenShot()
        {
            using (var driver = new ChromeDriver())
            {
                //打开baidu
                driver.Navigate().GoToUrl("http://www.baidu.com");
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);

                driver.FindElement(By.Id("kw")).SendKeys("selenium");
                driver.FindElement(By.Id("su")).Click();
                Thread.Sleep(2000);

                //截屏
                Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
                var path = AppContext.BaseDirectory + "screenshots";
                Console.WriteLine("path:" + path);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
                Console.WriteLine("fileName:" + fileName);
                var fullPath = path + "/" + fileName;
                ss.SaveAsFile(fullPath);
                Thread.Sleep(2000);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 执行javascript方法
        /// </summary>
        static void TestExecuteJavascript()
        {
            using (var driver = new ChromeDriver())
            {
                //打开baidu
                driver.Navigate().GoToUrl("http://www.baidu.com");
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);

                //弹出alert弹窗
                //driver.ExecuteScript("alert('hello selenium')");
                //Thread.Sleep(2000);

                //driver.SwitchTo().Alert().Accept();
                //Thread.Sleep(2000);

                //滚动条
                driver.FindElement(By.Id("kw")).SendKeys("selenium");
                driver.FindElement(By.Id("su")).Click();
                Thread.Sleep(2000);

                var js = "window.scrollTo(0, document.body.scrollHeight)";
                driver.ExecuteScript(js);
                Thread.Sleep(2000);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 动作链，包括一系列的鼠标和键盘操作
        /// </summary>
        static void TestActionChains()
        {
            using (var driver = new ChromeDriver())
            {
                //打开sahitest
                driver.Navigate().GoToUrl("http://sahitest.com/demo/clicks.htm");
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);

                #region 1，鼠标操作
                ////单击
                //var btnClick = driver.FindElement(By.XPath("/html/body/form/input[3]"));
                //new Actions(driver).Click(btnClick).Perform();
                //Thread.Sleep(2000);

                ////双击
                //var btnDoubleClick = driver.FindElement(By.XPath("/html/body/form/input[2]"));
                //new Actions(driver).DoubleClick(btnDoubleClick).Perform();
                //Thread.Sleep(2000);

                ////右击
                //var btnRightClick = driver.FindElement(By.XPath("/html/body/form/input[4]"));
                //new Actions(driver).ContextClick(btnRightClick).Perform();
                //Thread.Sleep(2000);

                #endregion

                #region 2，键盘操作
                var ta = driver.FindElement(By.XPath("/html/body/form/textarea"));
                ta.SendKeys("selenium");
                Thread.Sleep(2000);

                //ctrl+a
                ta.SendKeys(Keys.Control + "a");
                Thread.Sleep(2000);

                //ctrl+x
                ta.SendKeys(Keys.Control + "x");
                Thread.Sleep(2000);

                //ctrl+v
                ta.SendKeys(Keys.Control + "v");
                Thread.Sleep(2000);

                //移动鼠标焦点
                var btnClear = driver.FindElement(By.XPath("/html/body/form/input[1]"));
                new Actions(driver).MoveToElement(btnClear).Perform();
                Thread.Sleep(2000);

                #endregion

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 17种等待条件
        /// </summary>
        static void SeventeenWaitingCondition()
        {
            using (var driver = new ChromeDriver())
            {
                //打开form05.html
                driver.Navigate().GoToUrl("file:///" + AppContext.BaseDirectory + "/form05.html");
                driver.Manage().Window.Maximize();

                driver.FindElement(By.Id("btn1")).Click();

                //显式等待
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
                wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TextToBePresentInElementLocated(By.Id("id2"), "id 2"));

                var id2 = driver.FindElement(By.Id("id2"));
                Console.WriteLine(id2.Text);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 三种等待方式
        /// </summary>
        static void ThreeKindsWaiting()
        {
            using (var driver = new ChromeDriver())
            {
                #region 1，Thread.Sleep
                ////打开baidu
                //driver.Navigate().GoToUrl("https://www.baidu.com");
                //driver.Manage().Window.Maximize();
                //Thread.Sleep(2000);

                ////输入关键字
                //driver.FindElement(By.Id("kw")).SendKeys("selenium");
                //Thread.Sleep(2000);

                ////点击查询
                //driver.FindElement(By.Id("su")).Click();
                //Thread.Sleep(2000);
                #endregion

                #region 2，隐式等待
                //driver.Manage().Timeouts().ImplicitWait= TimeSpan.FromSeconds(10);

                //driver.Navigate().GoToUrl("https://www.baidu.com");
                //driver.Manage().Window.Maximize();

                ////输入关键字
                //driver.FindElement(By.Id("kw")).SendKeys("selenium");

                ////点击查询
                //driver.FindElement(By.Id("su")).Click();
                #endregion

                #region 3，显式等待
                driver.Navigate().GoToUrl("https://www.baidu.com");
                driver.Manage().Window.Maximize();

                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                IWebElement firstResult = wait.Until(e => e.FindElement(By.XPath("//*[@id='su']")));

                //输入关键字
                driver.FindElement(By.Id("kw")).SendKeys("selenium");

                //点击查询
                driver.FindElement(By.Id("su")).Click();
                #endregion

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// 测试弹窗，包括：警告框，确认框和提示框
        /// </summary>
        static void TestPopWin()
        {
            using (var driver = new ChromeDriver())
            {
                //打开form04.html
                driver.Navigate().GoToUrl("file:///" + AppContext.BaseDirectory + "/form04.html");
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);

                //1，alert
                //driver.FindElement(By.Id("alert")).Click();
                ////切换到alert
                //var alert = driver.SwitchTo().Alert();
                //Console.WriteLine(alert.Text);
                //Thread.Sleep(2000);

                //alert.Accept();

                //2，confirm
                //driver.FindElement(By.Id("confirm")).Click();
                //var confirm = driver.SwitchTo().Alert();
                //Console.WriteLine(confirm.Text);
                //Thread.Sleep(2000);

                ////confirm.Accept();//确定
                //confirm.Dismiss();//取消
                //Thread.Sleep(2000);

                //3，prompt
                driver.FindElement(By.Id("prompt")).Click();
                var prompt = driver.SwitchTo().Alert();
                Console.WriteLine(prompt.Text);
                Thread.Sleep(2000);

                prompt.Accept();
                Thread.Sleep(2000);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// select下拉列表
        /// </summary>
        static void TestSelect()
        {
            using (var driver = new ChromeDriver())
            {
                //打开form02.html
                driver.Navigate().GoToUrl("file:///" + AppContext.BaseDirectory + "/form03.html");
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);

                //下拉列表
                var selectProvince = driver.FindElement(By.Id("province"));
                var se = new SelectElement(selectProvince);
                se.SelectByIndex(3);
                Thread.Sleep(2000);

                se.SelectByValue("shanghai");
                Thread.Sleep(2000);

                se.SelectByText("广州");
                Thread.Sleep(2000);

                //提交表单
                driver.FindElement(By.Id("login")).Click();
                Thread.Sleep(2000);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// checkbox和radiobutton
        /// </summary>
        static void TestCheckBoxRadioButton()
        {
            using (var driver = new ChromeDriver())
            {
                //打开form02.html
                driver.Navigate().GoToUrl("file:///" + AppContext.BaseDirectory + "/form02.html");
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);

                //checkbox
                var ckBasketball = driver.FindElement(By.Name("basketball"));
                var ckBadminton = driver.FindElement(By.Name("badminton"));

                if (!ckBasketball.Selected)
                {
                    ckBasketball.Click();
                }
                if (!ckBadminton.Selected)
                {
                    ckBadminton.Click();
                }
                Thread.Sleep(2000);

                //radiobutton
                var genders = driver.FindElements(By.Name("gender"));
                if (!genders[0].Selected)
                {
                    genders[0].Click();
                }
                Thread.Sleep(2000);

                //提交表单
                driver.FindElement(By.Id("login")).Click();
                Thread.Sleep(2000);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// form表单
        /// </summary>
        static void TestForm()
        {
            using (var driver = new ChromeDriver())
            {
                //打开form01.html
                driver.Navigate().GoToUrl("file:///" + AppContext.BaseDirectory + "/form01.html");
                driver.Manage().Window.Maximize();
                Thread.Sleep(1000);

                driver.FindElement(By.Id("username")).SendKeys("admin");
                driver.FindElement(By.Id("pwd")).SendKeys("123456");
                Thread.Sleep(2000);

                //提交表单
                driver.FindElement(By.Id("login")).Click();
                Thread.Sleep(2000);

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// WebElement核心属性和方法
        /// </summary>
        static void WebElementCoreMethodProperty()
        {
            using (var driver = new ChromeDriver())
            {
                //打开sahitest
                driver.Navigate().GoToUrl("http://sahitest.com/demo/linkTest.htm");
                driver.Manage().Window.Maximize();
                Thread.Sleep(1000);

                #region 1，核心属性

                //var t1Input = driver.FindElement(By.Id("t1"));
                //Console.WriteLine(t1Input.GetType());
                //Console.WriteLine(t1Input.TagName);//tag name
                //Console.WriteLine(t1Input.Size);//size
                //Console.WriteLine(t1Input.Text);//text

                #endregion

                #region 2，核心方法

                var inputT1 = driver.FindElement(By.Id("t1"));
                inputT1.SendKeys("hello selenium");//SendKeys:输入内容
                Thread.Sleep(2000);

                inputT1.Clear();//Clear：清空内容
                Thread.Sleep(2000);

                Console.WriteLine(inputT1.GetAttribute("type"));//获取属性type
                Console.WriteLine(inputT1.GetAttribute("name"));//获取属性name
                Console.WriteLine(inputT1.GetAttribute("value"));//获取属性value
                Console.WriteLine(inputT1.GetAttribute("size"));//获取属性size
                Thread.Sleep(2000);

                Console.WriteLine(inputT1.GetCssValue("font"));//获取css属性font
                Console.WriteLine(inputT1.GetCssValue("color"));//获取css属性color
                Thread.Sleep(2000);

                #endregion

                //关闭
                driver.Quit();
            }
        }

        /// <summary>
        /// WebDriver核心方法和属性
        /// </summary>
        static void WebDriverCoreMethodProperty()
        {
            using (var driver = new ChromeDriver())
            {
                //打开baidu
                driver.Navigate().GoToUrl("https://www.baidu.com");
                driver.Manage().Window.Maximize();
                Thread.Sleep(1000);

                #region 核心属性
                //Console.WriteLine("当前Url："+driver.Url);//当前url
                //Console.WriteLine("当前浏览器窗口标题："+driver.Title);//当前浏览器窗口标题
                //Console.WriteLine("当前页面源代码："+driver.PageSource);//当前页面源码
                //Console.WriteLine("浏览器窗口句柄："+ string.Join(',', driver.WindowHandles));//浏览器窗口句柄
                #endregion

                #region 核心方法

                driver.FindElement(By.Id("kw")).SendKeys("selenium");
                driver.FindElement(By.CssSelector("#su")).Click();

                //后退
                driver.Navigate().Back();
                Thread.Sleep(2000);

                //刷新
                driver.Navigate().Refresh();
                Thread.Sleep(2000);

                //前进
                driver.Navigate().Forward();
                Thread.Sleep(2000);

                //关闭当前tab
                //driver.Close();

                #endregion

                //关闭浏览器
                driver.Quit();
            }
        }

        /// <summary>
        /// Selenium八大元素定位方法
        /// </summary>
        static void EightFindElementMethod()
        {
            //最佳实践：首选通过id定位，再是通过css选择器定位，然后是xpath。
            using (var driver = new ChromeDriver())
            {
                #region 1，通过id定位
                ////打开baidu
                //driver.Navigate().GoToUrl("https://www.baidu.com");
                //driver.Manage().Window.Maximize();
                //Thread.Sleep(1000);

                ////输入关键字selenium
                //driver.FindElementById("kw").SendKeys("selenium");
                //Thread.Sleep(1000);

                ////点击搜索按钮
                //driver.FindElementById("su").Click();
                //Thread.Sleep(3000); 
                #endregion

                #region 2，通过name定位
                //driver.Navigate().GoToUrl("https://www.baidu.com");
                //driver.Manage().Window.Maximize();
                //Thread.Sleep(1000);

                ////输入关键字selenium
                //driver.FindElementByName("wd").SendKeys("selenium");
                //Thread.Sleep(1000);

                ////点击搜索按钮
                //driver.FindElementById("su").Click();
                //Thread.Sleep(3000);
                #endregion

                #region 3和4，通过link text或Partial link text
                //driver.Navigate().GoToUrl("https://www.baidu.com");
                //driver.Manage().Window.Maximize();
                //Thread.Sleep(1000);

                ////输入关键字selenium
                //driver.FindElementByName("wd").SendKeys("selenium");
                //Thread.Sleep(1000);

                ////点击搜索按钮
                //driver.FindElementById("su").Click();
                //Thread.Sleep(2000);

                ////点击链接文本百度首页又回到首页
                ////driver.FindElementByLinkText("百度首页").Click();
                //driver.FindElementByPartialLinkText("首页").Click();
                //Thread.Sleep(2000);
                #endregion

                #region 5，通过xpath
                //driver.Navigate().GoToUrl("https://www.baidu.com");
                //driver.Manage().Window.Maximize();
                //Thread.Sleep(1000);

                ////输入关键字selenium
                //driver.FindElementByXPath("//*[@id='kw']").SendKeys("极客时间");
                //Thread.Sleep(1000);

                ////点击搜索按钮
                //driver.FindElementByXPath("//*[@id='su']").Click();
                //Thread.Sleep(2000);
                #endregion

                #region 6，css选择器
                //driver.Navigate().GoToUrl("https://www.baidu.com");
                //driver.Manage().Window.Maximize();
                //Thread.Sleep(1000);

                ////输入关键字selenium
                //driver.FindElementByCssSelector("#kw").SendKeys("selenium");
                //Thread.Sleep(1000);

                ////点击搜索按钮
                //driver.FindElementByCssSelector("#su").Click();
                //Thread.Sleep(2000);
                #endregion

                #region 7，通用方法
                driver.Navigate().GoToUrl("https://www.baidu.com");
                driver.Manage().Window.Maximize();
                Thread.Sleep(1000);

                //输入关键字selenium
                driver.FindElement(By.Id("kw")).SendKeys("selenium");
                Thread.Sleep(1000);

                //点击搜索按钮
                driver.FindElement(By.CssSelector("#su")).Click();
                Thread.Sleep(2000);
                #endregion

                //关闭浏览器
                driver.Quit();
            }
        }

        /// <summary>
        /// 第一个Selenium项目
        /// </summary>
        static void HelloSelenium()
        {
            using (var driver = new ChromeDriver())
            {
                //打开baidu
                driver.Navigate().GoToUrl("https://www.baidu.com");
                driver.Manage().Window.Maximize();
                Thread.Sleep(1000);

                //输入关键字selenium
                //driver.FindElementById("kw").SendKeys("selenium");
                Thread.Sleep(1000);

                //点击搜索按钮
                //driver.FindElementById("su").Click();
                Thread.Sleep(3000);

                //关闭浏览器
                driver.Quit();
            }
        }

        #region Private method

        /// <summary>
        /// Captures the element screen shot.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="uniqueName">Name of the unique.</param>
        /// <returns>returns the screenshot  image </returns>
        private static bool Login(ChromeDriver driver, IWebElement element)
        {
            Random rnd = new Random();

            //创建screenshots
            if (!Directory.Exists("screenshots"))
            {
                Directory.CreateDirectory("screenshots");
            }

            Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
            screenshot.SaveAsFile("screenshots/eastmoney-login.png", ScreenshotImageFormat.Png);

            Image img = Bitmap.FromFile("screenshots/eastmoney-login.png");
            Rectangle rect = new Rectangle();
            if (element != null)
            {
                // Get the Width and Height of the WebElement using
                int width = element.Size.Width;
                int height = element.Size.Height;

                // Get the Location of WebElement in a Point.
                // This will provide X & Y co-ordinates of the WebElement
                Point p = element.Location;

                // Create a rectangle using Width, Height and element location
                rect = new Rectangle(p.X, p.Y, width, height);
            }

            // croping the image based on rect.
            Bitmap bmpImage = new Bitmap(img);
            var cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat);
            cropedImag.Save("screenshots/eastmoney-validcode.png", ImageFormat.Png);

            //识别图形验证码
            var client = new RestClient("http://api.ttshitu.com/predict");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddParameter("username", "13640947887");
            request.AddParameter("password", "13640947887");
            //request.AddParameter("image", "图片的base64(注意不含：data:image/jpg;base64,直接图片base64编码)");
            //也可以是一个文件 2选1
            request.AddFile("image", "screenshots/eastmoney-validcode.png");
            //一、图片文字类型(默认 3 数英混合)：
            //1 : 纯数字
            //1001：纯数字2
            //2 : 纯英文
            //1002：纯英文2
            //3 : 数英混合
            //1003：数英混合2
            //4 : 闪动GIF
            //7 : 无感学习(独家)
            //11 : 计算题
            //1005:  快速计算题
            //16 : 汉字
            //32 : 通用文字识别(证件、单据)
            //66:  问答题
            //49 :recaptcha图片识别
            //二、图片旋转角度类型：
            //29 :  旋转类型

            //三、图片坐标点选类型：
            //19 :  1个坐标
            //20 :  3个坐标
            //21 :  3 ~ 5个坐标
            //22 :  5 ~ 8个坐标
            //27 :  1 ~ 4个坐标
            //48 : 轨迹类型
            //四、缺口识别
            //18：缺口识别（需要2张图 一张目标图一张缺口图），
            //33：单缺口识别（返回X轴坐标 只需要1张图）
            //五、拼图识别
            //53：拼图识别
            request.AddParameter("typeid", "1001");
            //其他参数根据需要从 http 接口文档中添加
            IRestResponse response = client.Execute(request);
            if (response == null || !response.IsSuccessful)
            {
                return false;
            }

            var predictResult = response.Content.FromJson<PredictResponse>();
            if (!predictResult.success)
            {
                return false;
            }

            var validCode = predictResult.data.result;
            Console.WriteLine(string.Format("验证码:{0}", validCode));

            driver.FindElement(By.Id("txtValidCode")).Clear();
            driver.FindElement(By.Id("txtValidCode")).SendKeys(validCode);
            Thread.Sleep(rnd.Next(2000, 3000));

            //提交表单
            driver.FindElement(By.Id("btnConfirm")).Click();
            Thread.Sleep(rnd.Next(1000, 2000));

            //显示等待表单提交
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            return wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.UrlContains(@"Trade/Buy"));
        }
        #endregion
    }
}
